# author： Zichen
# date: 2021-02-06
#vision: 1.0
# instruction：通过uid获取主播开播信息
# 导入库
from rich.console import Console
from urllib import request
import json
console = Console()  # 创建控制台

orange = '#ffb74d'
cyan = '#63e6be'
grey = '#bdbdbd'

# 用requests库的get()方法简明地获取网页信息。第一个函数返回一个网页内容---r.text.


def GetData(mid):
    url = "https://api.bilibili.com/x/space/acc/info?mid=%s&jsonp=jsonp" % mid  # 请求的url
    headers = {  # 请求的头部
        'origin': "https://space.bilibili.com",
        'referer': "https://space.bilibili.com/",
        'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36 Edg/88.0.705.63",
        'Host': "api.bilibili.com"
    }

    req = request.Request(url=url, headers=headers)  # GET无data项
    res = request.urlopen(req)
    res = str(res.read(), encoding='utf-8')  # 将返回的bytes类型转为str类型
    data = json.loads(res)  # 如果是json/dict类型,这一步可以转为dict类型,前提是从str转
#    console.log("[bold green]请求数据成功√：%s" % url)
#    console.print(data)
    return data  # 返回大字典data


def GetLivedata(data):  # 获得大字典data中的小字典data
    try:
        data_Liveroom = data.get('data').get('live_room')
        console.log('[bold green]已获得直播数据√')
        return data_Liveroom
    except:
        console.print_exception()


def GetLiveStatus(data):  # 获得小字典data中的直播状况

    #    console.log('[bold green]已获得直播状况√')
    try:
        LiveStatus = data.get('liveStatus')
        if LiveStatus == 0:
            return '[#bdbdbd]未直播'
        elif LiveStatus == 1:
            return '[#63e6be]正在直播'
    except:
        console.print_exception()


def GetLive_title(data):  # 获得小字典data中的直播开头
    #    console.log('[bold green]已获得直播开头√')
    try:
        Live_title = data.get('title')
        return(Live_title)
    except:
        console.print_exception()


def GetLive_url(data):  # 获得小字典data中的直播间链接
    #    console.log('[bold green]已获得直播链接√')
    try:
        Live_url = data.get('url')
        return(Live_url)
    except:
        console.print_exception()


def GetName_Mid(data):  # 获得大字典data中的主播名和uid
    try:
        Name = data.get('data').get('name')
        UID = str(data.get('data').get('mid'))
        NM_list = ['[%s]%s[/%s]' %
                   (cyan, Name, cyan), '[%s]%s[/%s]' % (cyan, UID, cyan)]
        return NM_list
    except:
        console.print_exception()
